<?php
class TinraosController extends AppController {

	var $name = 'Tinraos';
	var $autoRender=true; // renders nothing by default
	var $components = array('RequestHandler', 'Email', 'Session', 'MathCaptcha'); 
	var $paginate = array(
		'limit' => 10,
		'order' => array(
			'Tinrao.vitrixh' => 'asc'
		)
    );
	function index() {
		$this->Tinrao->recursive = 0;
		$this->set('tinraos', $this->paginate());
	}
	function admin_index() {
		$this->layout = 'admin';
		$this->Tinrao->recursive = 0;
		$this->paginate = array(
			'limit' => 10,
			'order' => array(
				'Tinrao.ngaydang' => 'desc',
				'Tinrao.vitrixh' => 'asc'
			)
		);
		$this->set('tinraos', $this->paginate());
	}
	/* function tinraosleft(){
		$data = $this->paginate('Tinrao');
		if (isset($this->params['requested'])) {
			return $data;
        }
		$this->set('data', $data);
	} */
	function tinraosright(){
		$data = $this->Tinrao->find('all', array('limit' => 10, 'order' => array('Tinrao.vitrixh' => 'asc'), 'conditions' => array('Tinrao.publish' => 1)));
		if (isset($this->params['requested'])) {
			return $data;
        }
		$this->set('data', $data);
	}
	function view($id = null) {
		$this->layout = 'detail';
		if (!$id) {
			$this->Session->setFlash(__('Invalid tinrao', true));
			$this->redirect(array('action' => 'index'));
		}
		$tinrao = $this->Tinrao->read(null, $id);
		$others = $this->Tinrao->find('all',  array('conditions' => array('Tinrao.duan_id' => $tinrao['Duan']['id'], 'Tinrao.publish' => 1)));
		$this->set('others', $others);
		$this->set('tinrao', $tinrao);
		$breadcrum = array( 
							'type' => $tinrao['Duan']['phanloai'],
							'tieudeduan' => $tinrao['Duan']['tieude'],
							'idduan' => $tinrao['Duan']['id'],
							'tieudetinrao' => $tinrao['Tinrao']['tieude'],
						  );
		$this->set('breadcrum', $breadcrum);
		$title = ''.$tinrao['Tinrao']['tieude'];
		$keyword = 'Du an Da Nang, Du an '.$tinrao['Duan']['tieude'].', mua ban du an '.$tinrao['Duan']['tieude'].', dau tu du an '.$tinrao['Duan']['tieude'].', thong tin du an '.$tinrao['Duan']['tieude'];
		if($tinrao['Duan']['phanloai'] == 0) $this->set('tab', 'listnormal');
		else $this->set('tab', 'listvip');
		$this->set('title', $title);
		$this->set('keyword', $keyword);
	}

	/* function add() {
		$this->layout = 'admin';
		if (!empty($this->data)) {
			$this->Tinrao->create();
			if ($this->Tinrao->save($this->data)) {
				$this->Session->setFlash(__('The tinrao has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The tinrao could not be saved. Please, try again.', true));
			}
		}
	} */
	function add() {
		$this->layout = 'detail';
		//App::import('Vendor', 'recaptchalib');
		//$privatekey = "6LcMKMkSAAAAAFWOhCeOvSAtiwGiSWJ767E3hlFY";
		//$resp = recaptcha_check_answer ($privatekey,
		//$_SERVER["REMOTE_ADDR"],
		//$_POST["recaptcha_challenge_field"],
		//$_POST["recaptcha_response_field"]);
		//$recapcha = $_POST['recapcha'];
		if(isset($_POST['idduan'])){
			$duan = $this->Tinrao->Duan->find('first', array('conditions' => array('Duan.id' => $_POST['idduan'])));
			if($_POST['addfrduan'] == 1){
				$link_redirect = 'http://'.$_SERVER['SERVER_NAME'].$this->webroot.'project-'.$_POST['idduan'].'/'.str_replace(" ","-",$duan['Duan']['tieude']).'.html';
			}else{
				$link_redirect = 'http://'.$_SERVER['SERVER_NAME'].$this->webroot.'tinraos/add';
			}
			if (!$this->MathCaptcha->validates($_POST['answercapcha'])) {
				$this->Session->setFlash("Câu trả lời chưa đúng!");
				//$this->redirect(array('controller'=>'duans', 'action' => 'view/'.$_POST['idduan']));
				$this->redirect($link_redirect);
			}else{
				
				$tieude = $_POST['tieude'];
				$idduan = $_POST['idduan'];
				$noidung = $_POST['noidung'];
				$tenlienhe = $_POST['tenlienhe'];
				$vitrixh = 9;
				$sdtlienhe = $_POST['sdtlienhe'];
				$email = $_POST['email'];
				$ngaydang = date('Y-m-d H:m:s');
				
				$i = $vitrixh;
				while(1){
					$tinrao = $this->Tinrao->find('first', array('conditions' => array('Tinrao.vitrixh' => $i)));
					if($tinrao){
						$i++;
					}else{
						break;
					}
				}
				$query = 'UPDATE tinraos SET vitrixh='.$i.' WHERE vitrixh = '.$vitrixh;
				$this->Tinrao->query($query);
				$query_insert = 'INSERT INTO tinraos (tieude, duan_id, noidung, tenlienhe, vitrixh, sdtlienhe, email, ngaydang)
								VALUES(\''.$tieude.'\', \''.$idduan.'\', \''.$noidung.'\', \''.$tenlienhe.'\', \''.$vitrixh.'\', \''.$sdtlienhe.'\', \''.$email.'\', \''.$ngaydang.'\')';
				if ($this->Tinrao->query($query_insert)) {
					$this->Session->setFlash(__('Tin rao của các bạn đã được gửi đến ban quản trị. Chúng tôi sẽ đăng sau khi kiểm duyệt. Cảm ơn bạn đã sử dụng website.', true));
					$this->redirect($link_redirect);
				} else {
					$this->Session->setFlash(__('Tin rao chưa được gửi thành công.', true));
				} 
			}
		}else{
			$this->set('tab', 'tinrao');
			$breadcrum = array( 
							'type' => '3',
							'tieudeduan' => '',
							'idduan' => '',
							'tieudetinrao' => '',
						  );
			$this->set('duans', $this->Tinrao->Duan->find('all'));
			$this->set('mathCaptcha', $this->MathCaptcha->generateEquation()); 
			$this->set('breadcrum', $breadcrum);
			$this->set('title', 'Đăng tin rao dự án');
			$this->set('keyword', 'Du an Da Nang, Dang tin rao du an');
		}
		
	}
	function changepublish(){
		$idtinrao = $_POST['idtinrao'];
		$published = $_POST['published'];
		$query = 'UPDATE tinraos SET publish = '.$published.' WHERE id = '.$idtinrao;
		if($this->Tinrao->query($query)){
			$this->redirect(array('action' => 'admin_index'));
		}
	}
	function change_vitrixh(){
		$idtinrao = $_POST['idtinrao'];
		$vitriedit = $_POST['vitrixh'];
		
		$i = $vitriedit;
		while(1){
			$tinrao = $this->Tinrao->find('first', array('conditions' => array('Tinrao.vitrixh' => $i)));
			if($tinrao){
				$i++;
			}else{
				break;
			}
			
		}
		$query = 'UPDATE tinraos SET vitrixh = '.$i.' WHERE vitrixh = '.$vitriedit;
		$this->Tinrao->query($query);
		$query = 'UPDATE tinraos SET vitrixh = '.$vitriedit.' WHERE id = '.$idtinrao;
		$this->Tinrao->query($query);
		$this->redirect(array('action' => 'admin_index'));
		
	}
	function admin_edit($id = null) {
		$this->layout = "admin";
		if(!isset($_POST['tieude'])&&!isset($_POST['noidung'])
			&&!isset($_POST['idduan'])&&!isset($_POST['tenlienhe'])
			&&!isset($_POST['vitrixh'])&&!isset($_POST['sdtlienhe'])
			&&!isset($_POST['email'])){
			//$this->data = $this->Duan->read(null, $id);
				$this->set('tinrao', $this->Tinrao->read(null, $id));
				$this->set('duans', $this->Tinrao->Duan->find('all'));
			}
		else{
			$id = $_POST['id'];
			$tieude = $_POST['tieude'];
			$noidung = $_POST['noidung'];
			$idduan = $_POST['idduan'];
			$tenlienhe = $_POST['tenlienhe'];
			$vitrixh = $_POST['vitrixh'];
			$sdtlienhe = $_POST['sdtlienhe'];
			$email = $_POST['email'];
			$ngaydang = date('Y-m-d');
			//$searchable = $this->changetv($tieude);
			$i = $vitrixh;
			while(1){
				$tinrao = $this->Tinrao->find('first', array('conditions' => array('Tinrao.vitrixh' => $i)));
				if($tinrao){
					$i++;
				}else{
					break;
				}
				
			}
			$query = 'UPDATE tinraos SET vitrixh = '.$i.' WHERE vitrixh = '.$vitrixh;
			$this->Tinrao->query($query);
			$query = 'UPDATE tinraos SET tieude = "'.$tieude.'", noidung = "'.$noidung.'", duan_id = '.$idduan.', tenlienhe = "'.$tenlienhe.'", vitrixh = '.$vitrixh.', sdtlienhe = '.$sdtlienhe.', email = "'.$email.'", ngaydang = "'.$ngaydang.'" WHERE id='.$id;
			if ($this->Tinrao->query($query)) {
				$this->Session->setFlash(__('Tin rao đã được cập nhật', true));
				$this->redirect(array('action' => 'admin_index'));
			} else {
				$this->Session->setFlash(__('Tin rao chưa được cập nhật', true));
			}
		}
	}
	/* function addtinrao(){
		$duans = $this->Tinrao->Duan->find('all');
		if(isset($this->params['requested'])){
            return $duans;
        }
	} */
	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid tinrao', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Tinrao->save($this->data)) {
				$this->Session->setFlash(__('The tinrao has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The tinrao could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Tinrao->read(null, $id);
		}
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Không tồn tại tin rao', true));
			$this->redirect(array('action'=>'admin_index'));
		}else{
			$tinr = $this->Tinrao->find('first', array('conditions' => array('Tinrao.id' => $id)));
			$i = $tinr['Tinrao']['vitrixh'] + 1;
			if ($this->Tinrao->delete($id)) {
				while(1){
					$tinrao = $this->Tinrao->find('first', array('conditions' => array('Tinrao.vitrixh' => $i)));
					if($tinrao){
						$query = 'UPDATE tinraos SET vitrixh = '.($i-1).' WHERE vitrixh = '.$i;
						$this->Tinrao->query($query);
						$i++;
					}else{
						break;
					}
					
				}
				$this->Session->setFlash(__('Tin rao được xóa thành công', true));
				$this->redirect(array('action'=>'admin_index'));
			}
			$this->Session->setFlash(__('Tin rao chưa được xóa', true));
			$this->redirect(array('action' => 'admin_index'));
		}
	}
	function admin_delete_all() {
		$this->autoRender = false;
		header('Content-type: application/json'); 
		$idtinraos = $_POST['idraovats'];
		$check = 1;
		for($i=0; $i<sizeof($idtinraos); $i++){
			if(!$this->Tinrao->delete($idtinraos[$i])){
				$check = 0;
			}
		}
		if($check == 0){
			echo json_encode(array('status'=>'fail'));
		}else{
			echo json_encode(array('status'=>'ok'));
		}
	}
	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for tinrao', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Tinrao->delete($id)) {
			$this->Session->setFlash(__('Tinrao deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Tinrao was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	function admin_search(){
		$this->layout = "admin";
		//search by ten lien he
		if($_POST['type'] == 'tenlienhe' || $_POST['type'] == 'tieude' || $_POST['type'] == 'noidung'){
			$this->paginate = array(
								'limit' => 25,
								'order' => array(
									'Tinrao.ngaydang' => 'desc'
								),
								'conditions' => array('Tinrao.'.$_POST['type'].' LIKE' => '%'.$_POST['inputsearch'].'%'),
							);
			$data = $this->paginate('Tinrao');
			 /* if($data){
				$this->Session->setFlash(__('Tìm thấy tin rao', true));
			} */
			$this->set('tinraos', $data);
		}else if($_POST['type'] == 'ngaydang'){
			$fromdate = date("Y-m-d H:i:s", strtotime( $_POST['fromdate']));;
			$todate = date("Y-m-d H:i:s", strtotime( $_POST['todate']));
			$this->paginate = array(
								'limit' => 25,
								'order' => array(
									'Tinrao.ngaydang' => 'desc'
								),
								'conditions' => array('Tinrao.'.$_POST['type'].' >=' => $fromdate, 'Tinrao.'.$_POST['type'].' <=' => $todate),
							);
			$data = $this->paginate('Tinrao');
			$this->set('tinraos', $data);
		}else{
			$this->Session->setFlash(__('Không tìm thấy tin rao', true));
		}
	}
	
}
?>